#include "importar.h"

importar::importar(){
	n_meshes=0;
}

importar::~importar(){
	int i;
	for(i=0;i<n_meshes;i++) mesh[i].~Mesh();	
	n_meshes=0;
}

void importar::import(const char *ruta){
  int line = 0, asteriscos=1;
  char staux[MAXLINE];
  FILE *f;
  
  if(!(f = fopen (ruta, "r")))
    {
      cerr << "File: " << ruta << " not found!" << endl;
      exit(-1);
    }
  
  while (fgets(staux, MAXLINE, f)!=NULL){

    line++;

    switch(staux[0]){

      // Comment.
    case '#':
    if (asteriscos==3){

        import_aux(f,line);
        n_meshes++;
        asteriscos=0;
    }else asteriscos++;
    break;
    case 'v': break;
    case 'f': break;
    default: break;

    }// End switch.

  }// End while.

  fclose (f);
}

void importar::import_aux(FILE *f,int line){
  char staux[MAXLINE];
  float a, b, c;
  GLdouble aux[3];
  float vx, vy, vz;
  while (fgets(staux, MAXLINE, f)!=NULL && staux[0]!='#'){

    line++;

    switch(staux[0]){

      // Comment.
    case '#':    break;
      // Vertex.
    case 'v': 

      // Read the x, y and z values.
      sscanf(&staux[2], "%f %f %f", &vx, &vy, &vz);

      aux[0] = vx; aux[1] = vy; aux[2] = vz;
      // Append a new vertex.
      mesh[n_meshes].verts.push_back(new Vertex3D(aux));

      break;

      // Face.
    case 'f': 

      sscanf(&staux[2], "%f %f %f", &a, &b, &c);

      // Store the vertex pointers.
      Vertex3D *vaux[]={verts[--a],verts[--b],verts[--c]};
      mesh[n_meshes].triangs.push_back(new Triangle(vaux));

      break;

   // default: break;

    }// End switch.

  }// End while.

}

int importar::get_nmeshes(){
	return n_meshes;
}

Mesh importar::get_mesh(int n){
	return mesh[n];
}

void importar::prueba(){
	printf("%d %d %d %d\n",mesh[0].verts[0],mesh[0].verts[2],mesh[0].triangs[0],mesh[0].triangs[2]);
}

